package com.ruoyi.knowledge.controller;

import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.knowledge.domain.KnowledgeFile;
import com.ruoyi.knowledge.service.IKnowledgeFileService;

/**
 * 知识库文件Controller
 *
 * @author waky
 */
@RestController
@Tag(name = "知识库文件管理")
@RequestMapping("/knowledge-base/{id}/files")
public class KnowledgeFileController extends BaseController {
    @Autowired
    private IKnowledgeFileService knowledgeFileService;

    /**
     * 查询知识库文件列表
     */
    @Operation(
            summary = "查询知识库文件列表",
            parameters = {
                    @Parameter(name = "id", description = "知识库ID")
            })
    @GetMapping
    public TableDataInfo list(@PathVariable("id") Long knowledgeId) {
        startPage();
        List<KnowledgeFile> list = knowledgeFileService.selectKnowledgeFilesByKnowledgeId(knowledgeId);

        // 只有在DEBUG级别下才输出详细的状态日志
        if (logger.isDebugEnabled() && list != null && !list.isEmpty()) {
            // 检查是否有处理中的文件，只有存在处理中的文件时才输出日志
            boolean hasProcessingFiles = list.stream()
                    .anyMatch(file -> "1".equals(file.getFileStatus()));

            if (hasProcessingFiles) {
                logger.debug("文件列表状态: {}", list.stream()
                        .map(file -> String.format("ID:%d, Name:%s, Status:%s",
                                file.getId(), file.getFilename(), file.getFileStatus()))
                        .toArray());
            }
        }

        return getDataTable(list);
    }

    /**
     * 上传知识库文件
     */
    @Operation(
            summary = "上传知识库文件",
            parameters = {
                    @Parameter(name = "id", description = "知识库ID"),
                    @Parameter(name = "file", description = "文件")
            })
    @Log(title = "知识库文件上传", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@PathVariable("id") Long knowledgeId, @RequestParam("file") MultipartFile file) {
        try {
            KnowledgeFile knowledgeFile = knowledgeFileService.uploadFile(knowledgeId, file,
                    SecurityUtils.getUsername());
            return success(knowledgeFile);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 删除知识库文件
     */
    @Operation(
            summary = "删除知识库文件",
            parameters = {
                    @Parameter(name = "fileId", description = "文件ID")
            })
    @Log(title = "知识库文件删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileId}")
    public AjaxResult remove(@PathVariable("fileId") Long fileId) {
        return toAjax(knowledgeFileService.deleteKnowledgeFileById(fileId));
    }

    /**
     * 批量删除知识库文件
     */
    @Operation(
            summary = "批量删除知识库文件",
            parameters = {
                    @Parameter(name = "fileIds", description = "文件ID列表")
            })
    @Log(title = "批量删除知识库文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch")
    public AjaxResult batchRemove(@RequestBody List<Long> fileIds) {
        return toAjax(knowledgeFileService.deleteKnowledgeFileByIds(fileIds));
    }

    /**
     * 处理文件向量化
     */
    @Operation(
            summary = "处理文件向量化",
            parameters = {
                    @Parameter(name = "fileId", description = "文件ID")
            })
    @Log(title = "知识库文件处理", businessType = BusinessType.UPDATE)
    @PostMapping("/{fileId}/process")
    public AjaxResult process(@PathVariable("fileId") Long fileId) {
        return toAjax(knowledgeFileService.processFile(fileId));
    }
}
